<template>
  <div>
    <van-nav-bar
      title="帐户设置"
      left-arrow
      fixed
      placeholder
      @click-left="goBack"
    >
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <div class="setting-box">
      <div class="head-box">
        <img v-lazy="user.avatar_url" alt="" />
        <p>{{ user.name }}</p>
      </div>
      <div class="profile-item">
        <ul>
          <li @click="showEditPassword = true">
            <span><van-icon name="edit" />修改密码</span>
            <van-icon name="arrow" />
          </li>
          <li @click="showEmailClick('email')">
            <span><van-icon name="envelop-o" />更换邮箱</span>
            <van-icon name="arrow" />
          </li>
          <li @click="showEmailClick('tel')">
            <span><van-icon name="phone" />绑定手机</span>
            <van-icon name="arrow" />
          </li>
        </ul>
      </div>
    </div>
    <van-popup
      v-model:show="showEditPassword"
      closeable
      position="bottom"
      :style="{ height: '50%' }"
      @close="editPasswordClose"
    >
      <van-form
        class="password-form"
        @submit="passwordSubmit"
        ref="editPasswordRef"
      >
        <van-field
          v-model="passwordForm.old_password"
          type="password"
          name="旧密码"
          label="旧密码"
          placeholder="旧密码"
          :rules="[{ validator: rulesPassword }]"
        />
        <van-field
          v-model="passwordForm.password"
          type="password"
          name="新密码"
          label="新密码"
          placeholder="新密码"
          :rules="[{ validator: rulesPassword }]"
        />
        <van-field
          v-model="passwordForm.password_confirmation"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ validator: rulesPassword }]"
        />
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </van-popup>
    <van-popup
      v-model:show="showTelEmail"
      closeable
      position="bottom"
      :style="{ height: '50%' }"
      @close="editEmailClose"
    >
      <van-form
        class="password-form"
        @submit="telEmailSubmit"
        ref="editEmailRef"
      >
        <van-field
          v-if="telAEditType === 'email'"
          class="old-email"
          v-model="TelEmailForm.email"
          name="邮箱"
          label="邮箱"
          placeholder="邮箱"
          :rules="[
            { validator: telAEditType === 'email' ? rulesEmail : rulesTel },
          ]"
        />
        <van-field
          v-else
          class="old-email"
          v-model="TelEmailForm.phone"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { validator: telAEditType === 'email' ? rulesEmail : rulesTel },
          ]"
        />
        <van-button
          :disabled="disabledRule"
          class="old-email-code"
          :type="disabledRule ? '' : 'warning'"
          size="small"
          @click="getTelEmailRule"
          >{{
            disabledRule ? disabledCount + '秒...' : '获取验证码'
          }}</van-button
        >
        <van-field
          v-model="TelEmailForm.code"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>
<script>
import { useRouter } from 'vue-router'
import { onMounted, reactive, ref, toRefs } from 'vue'
import { getUser } from '../../network/profile'
import { editPasswod, getRuleCode, editEmail, getTelCode, bindTel } from '../../network/setting'
import { Toast, Notify } from 'vant'
export default {
  setup () {
    const router = useRouter()
    const editPasswordRef = ref(null)
    const editEmailRef = ref(null)
    const state = reactive({
      user: {},
      showEditPassword: false,
      showTelEmail: false,
      telAEditType: '',
      passwordForm: {
        old_password: '',
        password: '',
        password_confirmation: ''
      },
      TelEmailForm: {
        code: '',
        email: '',
        phone: ''
      },
      disabledRule: false,
      disabledCount: 60
    })
    const init = () => {
      Toast.loading({ message: '加载中...', forbidClick: true })
      getUser().then(res => {
        console.log(res)
        state.user = res
        Toast.clear()
      })
    }
    onMounted(() => {
      init()
    })
    const rulesPassword = (val) => {
      if (/^\w{6,15}$/.test(val)) {
        return ''
      } else {
        return '密码不合法，长度6 ~ 15个字符'
      }
    }
    const passwordSubmit = () => {
      if (state.passwordForm.password !== state.passwordForm.password_confirmation) return Notify('两次密码不一至')
      editPasswod(state.passwordForm).then(res => {
        console.log(res)
        if (res.status === 204) {
          Toast.success('密码修改成功')
        }
      })
    }
    const editPasswordClose = () => {
      console.log(editPasswordRef.value)
      editPasswordRef.value.resetValidation()
    }
    const rulesEmail = (val) => {
      if (/^\w+@\w+\.\w+$/.test(val)) {
        return ''
      } else {
        return '邮箱不合法'
      }
    }
    const rulesTel = (val) => {
      if (/^1(3|5|6|8|9)\d{9}$/.test(val)) {
        return ''
      } else {
        return '手机号不合法'
      }
    }
    const countdown = () => {
      const tiem = setInterval(() => {
        if (state.disabledCount === 0) {
          clearInterval(tiem)
          state.disabledCount = 60
          state.disabledRule = false
        }
        state.disabledCount--
      }, 1000)
    }
    const getTelEmailRule = () => {
      if (state.telAEditType === 'email') {
        if (!/^\w+@\w+\.\w+$/.test(state.TelEmailForm.email)) return Notify('邮箱不符合规则')
        getRuleCode({ email: state.TelEmailForm.email }).then(res => {
          console.log(res)
          if (res.status === 204) {
            Toast('验证码已发送到您的邮箱')
            state.disabledRule = true
            countdown()
          }
        })
      } else if (state.telAEditType === 'tel') {
        if (!/^1(3|5|6|8|9)\d{9}$/.test(state.TelEmailForm.phone)) return Notify('手机号不符合规则')
        getTelCode({ phone: state.TelEmailForm.phone }).then(res => {
          console.log(res)
          if (res.status === 204) {
            Toast('验证码已发送到您的手机')
            state.disabledRule = true
            countdown()
          }
        })
      }
    }
    const telEmailSubmit = () => {
      if (state.telAEditType === 'email') {
        editEmail({ code: state.TelEmailForm.code, email: state.TelEmailForm.email }).then(res => {
          console.log(res)
          if (res.status === 204) {
            Toast('邮箱修改成功')
          }
        })
      } else if (state.telAEditType === 'tel') {
        bindTel({ code: state.TelEmailForm.code, phone: state.TelEmailForm.phone }).then(res => {
          console.log(res)
          if (res.status === 204) {
            Toast('绑定手机成功')
          }
        })
      }
    }
    const editEmailClose = () => {
      editEmailRef.value.resetValidation()
    }
    const showEmailClick = (type) => {
      state.telAEditType = type
      state.showTelEmail = true
    }
    const goBack = () => {
      router.go(-1)
    }
    return {
      ...toRefs(state),
      goBack,
      passwordSubmit,
      editPasswordRef,
      editPasswordClose,
      rulesPassword,
      editEmailClose,
      telEmailSubmit,
      rulesEmail,
      editEmailRef,
      getTelEmailRule,
      showEmailClick,
      rulesTel
    }
  }
}
</script>
<style scoped lang="less">
.setting-box {
  padding: 0 20px;
  .head-box {
    margin-top: 20px;
    img {
      width: 60px;
      height: 60px;
      margin-bottom: 5px;
    }
  }
}
.profile-item {
  margin-top: 35px;
  li {
    display: flex;
    justify-content: space-between;
    background-color: #f7f7f7;
    line-height: 40px;
    padding: 0 5px;
    margin-bottom: 20px;
    .van-icon {
      line-height: 40px;
    }
    span {
      .van-icon {
        margin-right: 10px;
        color: #b99342;
      }
    }
  }
}
.password-form {
  margin-top: 45px;
}
.old-email {
  width: 80%;
}
.old-email-code {
  position: absolute;
  top: 50px;
  right: 15px;
  z-index: 1;
}
</style>
